// 存储全局状态
const state = {
  scripts: [],
  selectedScript: null,
  isRunning: false,
  currentStepIndex: -1
};

// DOM准备完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  // 加载保存的脚本
  loadScripts();
  
  // 添加事件监听
  document.getElementById('run-script-btn').addEventListener('click', runScript);
  document.getElementById('stop-script-btn').addEventListener('click', stopScript);
  document.getElementById('clear-log-btn').addEventListener('click', clearLog);
  document.getElementById('script-form').addEventListener('submit', saveScript);
  document.getElementById('add-step-btn').addEventListener('click', addNewStep);
  
  // 监听步骤折叠/展开
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('toggle-step-btn')) {
      const stepEl = e.target.closest('.step');
      const bodyEl = stepEl.querySelector('.step-body');
      bodyEl.classList.toggle('show');
      e.target.textContent = bodyEl.classList.contains('show') ? '折叠' : '展开';
    }
  });
  
  // 监听步骤删除
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('remove-step-btn')) {
      const stepEl = e.target.closest('.step');
      stepEl.remove();
      updateStepIndices();
    }
  });
  
  // 监听步骤操作类型变化
  document.addEventListener('change', function(e) {
    if (e.target.classList.contains('step-action-select')) {
      const stepEl = e.target.closest('.step');
      const argsContainer = stepEl.querySelector('.step-args');
      updateStepArgsUI(argsContainer, e.target.value);
    }
  });
  
  // 监听来自后台脚本的消息
  chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    console.log('侧边栏收到消息:', message);
    
    if (message.type === 'script_status') {
      updateScriptStatus(message);
    } else if (message.type === 'script_step') {
      updateStepProgress(message);
    } else if (message.type === 'screenshot') {
      displayScreenshot(message.dataUrl);
    } else if (message.type === 'tool_result_reported') {
      logToolResult(message.data);
    }
  });
});

// 加载保存的脚本
function loadScripts() {
  chrome.runtime.sendMessage({ action: 'get_scripts' }, function(response) {
    if (response && response.success && response.scripts) {
      state.scripts = response.scripts;
      renderScriptList();
    }
  });
}

// 渲染脚本列表
function renderScriptList() {
  const scriptListEl = document.getElementById('script-list');
  scriptListEl.innerHTML = '';
  
  if (state.scripts.length === 0) {
    scriptListEl.innerHTML = '<div class="alert alert-info">还没有保存的脚本，请先创建一个</div>';
    return;
  }
  
  state.scripts.forEach(script => {
    const scriptEl = document.createElement('div');
    scriptEl.className = 'script-item';
    scriptEl.dataset.scriptId = script.id;
    scriptEl.innerHTML = `
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <strong>${script.name}</strong>
          <div class="text-muted small">${script.steps?.length || 0}个步骤</div>
        </div>
        <div class="btn-group btn-group-sm">
          <button class="btn btn-outline-primary edit-script-btn" data-script-id="${script.id}">编辑</button>
          <button class="btn btn-outline-danger delete-script-btn" data-script-id="${script.id}">删除</button>
        </div>
      </div>
    `;
    
    scriptEl.addEventListener('click', function(e) {
      if (!e.target.classList.contains('edit-script-btn') && !e.target.classList.contains('delete-script-btn')) {
        selectScript(script.id);
      }
    });
    
    scriptListEl.appendChild(scriptEl);
  });
  
  // 添加编辑和删除按钮的事件监听
  document.querySelectorAll('.edit-script-btn').forEach(btn => {
    btn.addEventListener('click', function(e) {
      e.stopPropagation();
      const scriptId = this.dataset.scriptId;
      editScript(scriptId);
    });
  });
  
  document.querySelectorAll('.delete-script-btn').forEach(btn => {
    btn.addEventListener('click', function(e) {
      e.stopPropagation();
      const scriptId = this.dataset.scriptId;
      deleteScript(scriptId);
    });
  });
}

// 选择脚本
function selectScript(scriptId) {
  // 从列表中移除所有active类
  document.querySelectorAll('.script-item').forEach(el => {
    el.classList.remove('active');
  });
  
  // 为选中的脚本添加active类
  const scriptEl = document.querySelector(`.script-item[data-script-id="${scriptId}"]`);
  if (scriptEl) {
    scriptEl.classList.add('active');
  }
  
  // 更新当前选中的脚本
  state.selectedScript = state.scripts.find(script => script.id === scriptId);
  
  if (state.selectedScript) {
    // 显示脚本详情
    document.getElementById('script-detail').style.display = 'block';
    document.getElementById('selected-script-name').textContent = state.selectedScript.name;
    document.getElementById('selected-script-desc').textContent = state.selectedScript.description || '无描述';
    
    // 渲染参数输入表单
    renderParamForm();
  } else {
    document.getElementById('script-detail').style.display = 'none';
  }
}

// 渲染参数输入表单
function renderParamForm() {
  const paramContainerEl = document.getElementById('param-container');
  paramContainerEl.innerHTML = '';
  
  const params = state.selectedScript.params || {};
  
  if (Object.keys(params).length === 0) {
    paramContainerEl.innerHTML = '<div class="alert alert-info">此脚本没有定义参数</div>';
    return;
  }
  
  const formEl = document.createElement('form');
  formEl.id = 'param-form';
  
  Object.entries(params).forEach(([paramName, paramDesc]) => {
    const div = document.createElement('div');
    div.className = 'mb-3';
    
    const label = document.createElement('label');
    label.className = 'form-label';
    label.textContent = paramDesc || paramName;
    
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'form-control';
    input.name = paramName;
    input.placeholder = `请输入${paramDesc || paramName}`;
    
    div.appendChild(label);
    div.appendChild(input);
    formEl.appendChild(div);
  });
  
  paramContainerEl.appendChild(formEl);
}

// 运行脚本
function runScript() {
  if (!state.selectedScript) {
    addLog('错误', '请先选择一个脚本', 'error');
    return;
  }
  
  if (state.isRunning) {
    addLog('警告', '已有脚本正在运行', 'warning');
    return;
  }
  
  // 收集参数
  const params = {};
  const paramForm = document.getElementById('param-form');
  if (paramForm) {
    const formData = new FormData(paramForm);
    for (const [key, value] of formData.entries()) {
      params[key] = value;
    }
  }
  
  // 显示进度条和停止按钮
  document.getElementById('progress-container').style.display = 'block';
  document.getElementById('run-script-btn').style.display = 'none';
  document.getElementById('stop-script-btn').style.display = 'block';
  
  // 更新状态
  state.isRunning = true;
  state.currentStepIndex = -1;
  
  // 清空日志并添加开始执行的日志
  clearLog();
  addLog('信息', `开始执行脚本: ${state.selectedScript.name}`, 'info');
  
  // 发送消息给后台脚本执行
  chrome.runtime.sendMessage(
    {
      action: 'run_script',
      script: state.selectedScript, 
      params: params
    },
    function(response) {
      console.log('脚本执行响应:', response);
      
      // 重置UI状态
      document.getElementById('progress-container').style.display = 'none';
      document.getElementById('run-script-btn').style.display = 'block';
      document.getElementById('stop-script-btn').style.display = 'none';
      
      // 更新状态
      state.isRunning = false;
      
      if (response.success) {
        addLog('成功', '脚本执行完成', 'success');
      } else {
        addLog('错误', `脚本执行失败: ${response.error}`, 'error');
      }
    }
  );
}

// 停止脚本
function stopScript() {
  if (!state.isRunning) return;
  
  chrome.runtime.sendMessage({ action: 'stop_script' }, function(response) {
    if (response && response.success) {
      addLog('信息', '用户手动停止脚本执行', 'info');
      
      // 重置UI状态
      document.getElementById('progress-container').style.display = 'none';
      document.getElementById('run-script-btn').style.display = 'block';
      document.getElementById('stop-script-btn').style.display = 'none';
      
      // 更新状态
      state.isRunning = false;
    }
  });
}

// 更新脚本执行状态
function updateScriptStatus(message) {
  switch (message.status) {
    case 'running':
      addLog('信息', message.message || '脚本开始执行', 'info');
      break;
      
    case 'completed':
      addLog('成功', '脚本执行完成', 'success');
      // 重置UI状态
      document.getElementById('progress-container').style.display = 'none';
      document.getElementById('run-script-btn').style.display = 'block';
      document.getElementById('stop-script-btn').style.display = 'none';
      state.isRunning = false;
      break;
      
    case 'error':
      addLog('错误', message.error || '脚本执行出错', 'error');
      // 重置UI状态
      document.getElementById('progress-container').style.display = 'none';
      document.getElementById('run-script-btn').style.display = 'block';
      document.getElementById('stop-script-btn').style.display = 'none';
      state.isRunning = false;
      break;
      
    case 'stopped':
      addLog('信息', message.message || '脚本执行已停止', 'info');
      // 重置UI状态(如果需要)
      break;
  }
}

// 更新步骤进度
function updateStepProgress(message) {
  const { stepIndex, totalSteps, stepInfo } = message;
  
  // 更新进度条
  const progressBar = document.getElementById('progress-bar');
  const progressStatus = document.getElementById('progress-status');
  
  const percent = Math.round((stepIndex + 1) / totalSteps * 100);
  progressBar.style.width = `${percent}%`;
  progressBar.setAttribute('aria-valuenow', percent);
  progressBar.textContent = `${percent}%`;
  
  // 更新状态文本
  progressStatus.textContent = `执行步骤 ${stepIndex + 1}/${totalSteps}: ${getStepDescription(stepInfo)}`;
  
  // 添加日志
  addLog('信息', `执行步骤 ${stepIndex + 1}/${totalSteps}: ${getStepDescription(stepInfo)}`, 'info');
  
  // 更新当前步骤索引
  state.currentStepIndex = stepIndex;
}

// 获取步骤描述
function getStepDescription(step) {
  switch (step.action) {
    case 'navigate_to_url':
      return `打开网址: ${step.args.url}`;
    case 'click':
      return `点击元素: ${step.args.selector}`;
    case 'input':
      return `输入文本: ${step.args.text} (到元素: ${step.args.selector})`;
    case 'wait':
      return `等待 ${step.args.milliseconds}ms`;
    case 'extract':
      return `提取内容: ${step.args.selector}`;
    case 'execute_js':
      return `执行JavaScript代码`;
    case 'screenshot':
      return `截取屏幕截图`;
    default:
      return `执行 ${step.action}`;
  }
}

// 显示截图
function displayScreenshot(dataUrl) {
  const container = document.getElementById('screenshot-container');
  const img = document.getElementById('screenshot-img');
  
  img.src = dataUrl;
  container.style.display = 'block';
  
  addLog('信息', '页面截图已更新', 'info');
}

// 记录工具执行结果
function logToolResult(data) {
  const { name, args, result } = data;
  
  if (result.success) {
    addLog('成功', `工具 ${name} 执行成功: ${JSON.stringify(result)}`, 'success');
  } else {
    addLog('错误', `工具 ${name} 执行失败: ${result.error}`, 'error');
  }
}

// 添加日志
function addLog(type, message, className) {
  const logContainer = document.getElementById('log-container');
  
  const logEntry = document.createElement('div');
  logEntry.className = `log-entry log-${className}`;
  
  const timestamp = new Date().toLocaleTimeString();
  logEntry.innerHTML = `[${timestamp}] [${type}] ${message}`;
  
  logContainer.appendChild(logEntry);
  logContainer.scrollTop = logContainer.scrollHeight;
}

// 清除日志
function clearLog() {
  const logContainer = document.getElementById('log-container');
  logContainer.innerHTML = '';
}

// 保存脚本
async function saveScript(e) {
  e.preventDefault();
  
  const nameInput = document.getElementById('script-name');
  const descInput = document.getElementById('script-desc');
  const paramsInput = document.getElementById('script-params');
  
  if (!nameInput.value.trim()) {
    alert('请输入脚本名称');
    return;
  }
  
  // 解析参数定义
  let params = {};
  try {
    if (paramsInput.value.trim()) {
      params = JSON.parse(paramsInput.value);
    }
  } catch (error) {
    alert('参数定义JSON格式错误: ' + error.message);
    return;
  }
  
  // 收集脚本步骤
  const steps = [];
  document.querySelectorAll('#steps-container .step').forEach(stepEl => {
    const actionSelect = stepEl.querySelector('.step-action-select');
    const action = actionSelect.value;
    
    // 收集步骤参数
    const args = {};
    stepEl.querySelectorAll('.step-args input, .step-args textarea, .step-args select').forEach(input => {
      args[input.name] = input.value;
    });
    
    // 收集延迟
    const delay = parseInt(stepEl.querySelector('.step-delay').value) || 0;
    
    steps.push({
      action,
      args,
      delay
    });
  });
  
  // 创建脚本对象
  const script = {
    id: state.selectedScript?.id, // 如果是编辑现有脚本，保留ID
    name: nameInput.value.trim(),
    description: descInput.value.trim(),
    params,
    steps
  };
  
  // 发送消息保存脚本
  chrome.runtime.sendMessage({ action: 'save_script', script }, function(response) {
    if (response && response.success) {
      alert('脚本保存成功');
      loadScripts(); // 重新加载脚本列表
      
      // 切换到运行标签页
      const runTab = document.getElementById('run-tab');
      bootstrap.Tab.getOrCreateInstance(runTab).show();
    } else {
      alert('保存失败: ' + (response?.error || '未知错误'));
    }
  });
}

// 编辑脚本
function editScript(scriptId) {
  const script = state.scripts.find(s => s.id === scriptId);
  if (!script) return;
  
  state.selectedScript = script;
  
  // 填充表单
  document.getElementById('script-name').value = script.name || '';
  document.getElementById('script-desc').value = script.description || '';
  document.getElementById('script-params').value = script.params ? JSON.stringify(script.params, null, 2) : '';
  
  // 清空并重建步骤UI
  const stepsContainer = document.getElementById('steps-container');
  stepsContainer.innerHTML = '';
  
  if (script.steps && script.steps.length > 0) {
    script.steps.forEach((step, index) => {
      addStepUI(step, index);
    });
  }
  
  // 切换到编辑标签页
  const editTab = document.getElementById('edit-tab');
  bootstrap.Tab.getOrCreateInstance(editTab).show();
}

// 删除脚本
function deleteScript(scriptId) {
  if (!confirm('确定要删除这个脚本吗？')) return;
  
  const updatedScripts = state.scripts.filter(s => s.id !== scriptId);
  
  chrome.storage.local.set({ testScripts: updatedScripts }, function() {
    alert('脚本已删除');
    state.scripts = updatedScripts;
    
    if (state.selectedScript && state.selectedScript.id === scriptId) {
      state.selectedScript = null;
      document.getElementById('script-detail').style.display = 'none';
    }
    
    renderScriptList();
  });
}

// 添加新步骤
function addNewStep() {
  const stepsContainer = document.getElementById('steps-container');
  const index = stepsContainer.children.length;
  
  addStepUI({ action: 'navigate_to_url', args: {}, delay: 0 }, index);
}

// 添加步骤UI
function addStepUI(step, index) {
  const stepsContainer = document.getElementById('steps-container');
  
  // 获取步骤模板内容
  const template = document.getElementById('step-template');
  const templateContent = template.innerHTML;
  
  // 创建新的步骤元素
  const stepDiv = document.createElement('div');
  stepDiv.className = 'step mb-3';
  stepDiv.dataset.stepIndex = index;
  
  // 填充模板
  let stepHtml = templateContent
    .replace('${index}', index)
    .replace('${index + 1}', index + 1)
    .replace('${action}', getActionName(step.action));
  
  stepDiv.innerHTML = stepHtml;
  
  // 设置正确的操作类型
  const actionSelect = stepDiv.querySelector('.step-action-select');
  actionSelect.value = step.action;
  
  // 更新操作参数UI
  const argsContainer = stepDiv.querySelector('.step-args');
  updateStepArgsUI(argsContainer, step.action);
  
  // 填充操作参数值
  setTimeout(() => {
    Object.entries(step.args || {}).forEach(([key, value]) => {
      const input = argsContainer.querySelector(`[name="${key}"]`);
      if (input) {
        input.value = value;
      }
    });
  }, 0);
  
  // 设置延迟值
  const delayInput = stepDiv.querySelector('.step-delay');
  delayInput.value = step.delay || 0;
  
  // 添加到容器
  stepsContainer.appendChild(stepDiv);
}

// 更新步骤参数UI
function updateStepArgsUI(container, action) {
  // 获取对应动作的参数模板
  const template = document.getElementById(`args-${action}-template`);
  if (!template) {
    container.innerHTML = '<div class="alert alert-warning">该操作类型没有参数</div>';
    return;
  }
  
  container.innerHTML = template.innerHTML;
}

// 更新步骤索引
function updateStepIndices() {
  const steps = document.querySelectorAll('#steps-container .step');
  steps.forEach((step, index) => {
    step.dataset.stepIndex = index;
    step.querySelector('.step-index').textContent = index + 1;
  });
}

// 获取操作类型的显示名称
function getActionName(action) {
  const actionMap = {
    'navigate_to_url': '打开网址',
    'click': '点击元素',
    'input': '输入文本',
    'wait': '等待时间',
    'extract': '提取内容',
    'execute_js': '执行JS',
    'screenshot': '屏幕截图'
  };
  
  return actionMap[action] || action;
} 